﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Fleck;
using System.Web.Script.Serialization;

namespace WebSocketServer
{
    public partial class WebSocketServer : Form
    {
        public WebSocketServer()
        {
            Form.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private Fleck.IWebSocketServer server = null;

        private List<WebChat_Msg> socketList = new List<WebChat_Msg>();
        private JavaScriptSerializer jsonHelper = new JavaScriptSerializer() { MaxJsonLength = int.MaxValue };

        private void frmMain_Load(object sender, EventArgs e)
        {

        }


        void StartService()
        {
            server = new Fleck.WebSocketServer("ws://" + txt_ServerHost.Text.Trim());
            server.Start(socket =>
            {
                //连接
                socket.OnOpen = () =>
                {
                    WebChat_Msg wbm = new WebChat_Msg();
                    wbm.web_Socket = socket;
                    socketList.Add(wbm);
                    Console.WriteLine("Open!");
                    this.Text ="在线人数："+ socketList.Count.ToString();
                };


                //关闭
                socket.OnClose = () =>
                {
                    WebChat_Msg wbm = new WebChat_Msg();
                    wbm.web_Socket = socket;                   
                    socketList.RemoveAt(socketList.FindIndex(delegate (WebChat_Msg w)//删除离线的
                    {
                        return w.web_Socket.ConnectionInfo.Id == wbm.web_Socket.ConnectionInfo.Id;
                    }));
                    pushList(wbm);
                    Console.WriteLine("Close!");
                    this.Text = "在线人数：" + socketList.Count.ToString();
                };

                //接受值
                socket.OnMessage = message =>
                {
                    try
                    {
                        WebChat_Msg wbm = jsonHelper.Deserialize<WebChat_Msg>(message);
                        wbm.web_Socket = socket;
                        cmdParser(wbm);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                };
            });
        }


        /// <summary>
        /// 传过来的参数解析
        /// </summary>
        /// <param name="wbm"></param>
        private  void cmdParser(WebChat_Msg wbm)
        {
            switch (wbm.msg_type)
            {
                case 0: //文字
                    sendMsg(wbm);
                    break;
                case 1: //表情
                    sendMsg(wbm);
                    break;
                case 2: //图片
                    sendMsg(wbm);
                    break;
                case 3://返回用户列表
                    WebChat_Msg L = socketList.Find(delegate (WebChat_Msg w)
                    {
                        return w.web_Socket.ConnectionInfo.Id == wbm.web_Socket.ConnectionInfo.Id;
                    });
                    if (L != null)//觉得这里没啥用；不知道啥时候写的；回头再查吧
                    {
                        L.u_name = wbm.u_name;//保存用户的名字
                        L.u_face = wbm.u_face;//保存用户头像
                    }
                    pushList(wbm);
                    break;
            }

        }



        /// <summary>
        /// 用户消息转发
        /// </summary>
        /// <param name="wbm"></param>
        public void sendMsg(WebChat_Msg wbm)
        {
            WebChat_Msg tempMsg = socketList.Find(delegate (WebChat_Msg w)
            {
                return w.web_Socket.ConnectionInfo.Id == wbm.u_rid;//
            });
            if (tempMsg != null)
            {
                wbm.web_Socket = null;//必须清空；因为此类型无法转换json
                ResultObj obj = new ResultObj();
                obj.code = 200;
                obj.type = wbm.msg_type;
                obj.data = wbm;
                tempMsg.web_Socket.Send(jsonHelper.Serialize(obj)); //找到接受者；把消息发送给接受者
            }
        }

        /// <summary>
        /// 获取在线列表
        /// </summary>
        /// <returns></returns>
        public ResultObj onlineList(WebChat_Msg wbm)
        {
            ResultObj  obj = new ResultObj ();
            List<WebChat_Msg> list = null;
            if (socketList.Count > 0)
            {
                list=new List<WebChat_Msg>();
                for (int i = 0; i < socketList.Count; i++)
                {
                    WebChat_Msg msg = new WebChat_Msg();//返回用户信息
                    msg.u_name = socketList[i].u_name;
                    msg.u_id = socketList[i].web_Socket.ConnectionInfo.Id;
                    msg.u_ip = socketList[i].web_Socket.ConnectionInfo.ClientIpAddress;
                    msg.u_face = socketList[i].u_face;
                    list.Add(msg);
                }
            }
            if (list != null)
            {
                obj.data = list;
                obj.code = 200;
            }
            else
            {
                obj.code = 400;
            }
            obj.data = list;
            obj.type = 3;
            return obj;
        }


        /// <summary>
        /// 推送在线列表
        /// </summary>
        public void pushList(WebChat_Msg wbm)
        {
            for (int i = 0; i < socketList.Count; i++)
            {
                socketList[i].web_Socket.Send(jsonHelper.Serialize(onlineList(wbm)));
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (server == null)
            {
                StartService();
                btn_StartServer.Text = "停止服务";
                txt_ServerHost.Enabled = false;
            }
            else
            {
                server.Dispose();
                server = null;
                btn_StartServer.Text = "开启服务";
                txt_ServerHost.Enabled = true;
            }

        }
    }
}







//socket.OnBinary = file => {

//    string path = ("D:/test.txt");
//    //创建一个文件流
//    FileStream fs = new FileStream(path, FileMode.Create);

//    //将byte数组写入文件中
//    fs.Write(file, 0, file.Length);
//    //所有流类型都要关闭流，否则会出现内存泄露问题
//    fs.Close();
//};

//e.preventDefault();
//var val = input.value;
//ws.send(val);
//input.value = "";
